/* 新增图纸 */
<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    :bodyStyle="bodyStyle"
    style="top:15%"
  >
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        关闭
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" id="customerModal">
        <!-- <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品序号">
            <a-input placeholder="请输入唯一序号" v-decorator.trim="['serialNo', validatorRules.required]" />
          </a-form-item>
        </a-col> -->
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户名">
            <a-input placeholder="请输入客户名" v-decorator.trim="['customerName', validatorRules.name]" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品名称">
            <a-input placeholder="请输入产品名称" v-decorator.trim="['productName', validatorRules.name]" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格">
            <a-input placeholder="请输入规格" v-decorator.trim="['specifications']" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item
            :labelCol="{
              xs: { span: 24 },
              sm: { span: 3 }
            }"
            :wrapperCol="wrapperCol"
            label="CAD上传"
          >
            <!-- accept="image/png,image/jpeg,image/webp,image/jpg" -->
            <a-upload
              name="file"
              :beforeUpload="beforeUpload"
              :multiple="false"
              :headers="tokenHeader"
              :action="importExcelUrl"
              :showUploadList="false"
              v-decorator.trim="['cad']"
              @change="myhandleImportExcel"
            >
              <a-button> <a-icon type="upload" />上传</a-button>
              <span v-if="this.model.cad != null" style="margin-left:10px"
                >文件已存在，如再次上传将覆盖上次上传内容</span
              >
            </a-upload>
          </a-form-item>
        </a-col>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import pick from 'lodash.pick'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { addtz, audittz, checkSupplier } from '@/api/api'
import { autoJumpNextInput } from '@/utils/util'
export default {
  name: 'addDrawing',
  mixins: [JeecgListMixin],
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      defaultFileList: null,
      isReadOnly: false,
      bodyStyle: {
        padding: '20',
        height: window.innerHeight * 0.5 + 'px',
        'overflow-y': 'auto'
      },
      labelCol: {
        xs: { span: 24 / 2 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 / 2 },
        sm: { span: 16 }
      },
      defaultFileList: null,
      url: {
        importExcelUrl: '/systemConfig/upload' + '?' + `biz=cad`
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        name: {
          rules: [
            { required: true, message: '请输入!' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
            { validator: this.validateSupplierName }
          ]
        },
        required: {
          rules: [{ required: true, message: '请输入!' }]
        }
      }
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
      // return `api${this.url.importExcelUrl}`
    }
  },
  created() {},
  methods: {
    //图片上传前做限制
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        // let isType =
        //   file.type === 'image/jpg' ||
        //   file.type === 'image/jpeg' ||
        //   file.type === 'image/png' ||
        //   file.type === 'image/webp'
        // if (!isType) {
        //   this.$message.error('格式错误,只能上传jpg、jpeg、png、webp')
        //   return reject(false)
        // }
        return resolve(true)
      })
    },
    add() {
      this.edit()
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.defaultFileList = this.model.cad
      this.visible = true
      console.log(this.model)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'customerName', 'productName', 'specifications'))
        autoJumpNextInput('customerModal')
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    /* 导入 */
    myhandleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200 || info.file.response.code === 10000) {
            this.$message.success(`${info.file.name} 文件上传成功` || info.file.response.data)
            this.defaultFileList = info.file.response.data
            console.log('defaultFileList:', this.defaultFileList)
          } else {
            this.$message.warning(info.file.response.message)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          console.log(this.model)
          let formData = Object.assign(this.model, values)
          if (!this.defaultFileList || this.defaultFileList.length == 0) {
            that.$message.warn('请上传')
            that.confirmLoading = false
            return
          }
          formData.id = this.model.id
          formData.cad = this.defaultFileList
          //   formData.recordDate = this.$moment(formData.recordDate).format('YYYY-MM-DD')
          let obj
          if (!this.model.id) {
            obj = addtz(formData)
          } else {
            obj = audittz(formData)
          }
          obj
            .then(res => {
              if (res.code === 200 || res.code === 10000) {
                this.$message.success('保存成功')
                that.$emit('ok')
              } else {
                that.$message.warning(res.message || '操作失败')
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then(res => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback('名称已经存在')
          }
        } else {
          callback(res.data)
        }
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
